package 字节跳动手撕.A;

import java.util.HashMap;
import java.util.Map;
import java.util.Stack;

//package 字节跳动寿司.A;
//
public class Main {
    public  static  String countOfAtoms(String formula) {
       //操作字符串  就没有头绪
        Map<String, Integer> map = new HashMap<>();
        Stack<Character> stack = new Stack<>();
        for (int i = 0; i < formula.length(); i++) {
            char ch = formula.charAt(i);
            //遇到左边的括号需要记录之前的值进来
            if (ch == '(') {
                String str="";
                while (!stack.isEmpty()&&stack.peek() != ')') {
                    str+=stack.pop();
                }
                StringBuilder sb=new StringBuilder(str).reverse();
                map.put(sb.toString(), map.getOrDefault(sb.toString(), 0) + 1);
                stack.push(ch);
            }
            else if (ch == ')') {
                while (!stack.isEmpty() && stack.peek() != '(') {
                    int x=formula.charAt(i+1) - '0';
                    map.put(String.valueOf(stack.pop()), map.getOrDefault(stack.peek(), 0) + x);
                }
            }else if (ch>='2' && ch<='9') {
                if (stack.isEmpty()&&formula.charAt(i-1)!=')'){
                    map.put(String.valueOf(stack.pop()), map.getOrDefault(stack.peek(), 0) + ch-'0');
                }
            }
            else{
                stack.push(ch);
            }
        }
        System.out.println(map);
        return  "";
    }

    public static void main(String[] args) {
        countOfAtoms("H2O");
        countOfAtoms("Mg(OH)2");
        countOfAtoms("K4(ON(SO3)2)2");
    }
}
